<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/2/26
 * Time: 9:48
 */

namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\admin\model\ApiResponse;
use app\common\model\conf\ConfigUserRegisterGift;
use app\common\model\SysConfiguration;
use think\Request;

class Configure extends AdminController
{
    public function index(Request $request) {
        if ($request->isGet()) {
            $name = $request->param('name');
            if ($name) {
                $sc = SysConfiguration::get($name);
                $config = $sc->config ?? SysConfiguration::newConfig($name);
                return ApiResponse::success($config);
            } else {
                $list = SysConfiguration::list();
                return ApiResponse::success($list);
            }
        } elseif ($request->isPost()) {
            $name = $request->post('name');
            $config = $request->post('config');

            if (isset(SysConfiguration::$NameTitles[$name])) {
                $sc = SysConfiguration::get($name);
                if (empty($sc)) {
                    $sc = new SysConfiguration();
                    $sc->name = $name;
                }
                $config = json_decode($config);
                $sc->config = new ConfigUserRegisterGift($config);
                $sc->save();
                return ApiResponse::success();
            } else {
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'无效配置项');
            }
        } else {
            return json(null,405);
        }
    }


}